'use client';

import React, { createContext, useContext, useEffect, ReactNode, useState } from 'react';

interface VoiceContextType {
  selectedVoice: string;
  setSelectedVoice: (voice: string) => void;
}

const VoiceContext = createContext<VoiceContextType | undefined>(undefined);

interface VoiceProviderProps {
  children: ReactNode;
}

export function VoiceProvider({ children }: VoiceProviderProps) {
  const [selectedVoice, setSelectedVoiceState] = useState('21m00Tcm4TlvDq8ikWAM');

  // Load saved voice from localStorage on mount
  useEffect(() => {
    const savedVoice = localStorage.getItem('preferredVoice');
    if (savedVoice) {
      setSelectedVoiceState(savedVoice);
    }
  }, []);

  // Save voice to localStorage and update state
  const setSelectedVoice = (voice: string) => {
    setSelectedVoiceState(voice);
    localStorage.setItem('preferredVoice', voice);
  };

  return (
    <VoiceContext.Provider value={{ selectedVoice, setSelectedVoice }}>
      {children}
    </VoiceContext.Provider>
  );
}

export function useVoice() {
  const context = useContext(VoiceContext);
  if (context === undefined) {
    throw new Error('useVoice must be used within a VoiceProvider');
  }
  return context;
}
